﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kata.RomanNumerals
{
    public static class RomanNumerals
    {
        public static string ToRomanNumerals(this int value)
        {
            var result = new StringBuilder();

            while (value > 0)
            {
                foreach (var symbol in symbols)
                {
                    if (symbol.Key <= value)
                    {
                        result.Append(symbol.Value);
                        value -= symbol.Key;
                        break;
                    }
                }
            }

            return result.ToString();
        }

        public static int ToInteger(string romanNumerals)
        {
            var result = 0;
            var builder = new StringBuilder(romanNumerals);

            while (builder.Length > 0)
            {
                var stringValue = builder.ToString();

                foreach (var symbol in symbols)
                {
                    if (stringValue.StartsWith(symbol.Value))
                    {
                        builder.Remove(0, symbol.Value.Length);
                        result += symbol.Key;
                        break;
                    }
                }
            }

            return result;
        }

        static readonly IEnumerable<KeyValuePair<int, string>> symbols = new Dictionary<int, string>()
        {
            { 1000, "M" },
            { 900, "CM" },
            { 500, "D" },
            { 400, "CD" },
            { 100, "C" },
            { 90, "XC" },
            { 50, "L" },
            { 40, "XL" },
            { 10, "X" },
            { 9, "IX" },
            { 5, "V" },
            { 4, "IV" },
            { 1, "I" }
        };
    }
}